package org.lc.stk.web.controller.baseInfo;

import java.util.List;
import java.util.stream.Collectors;

import org.lc.stk.model.baseInfo.Department;
import org.lc.stk.service.baseInfo.DepartmentService;
import org.lc.stk.web.dto.department.CreateDepartmentRequest;
import org.lc.stk.web.dto.department.DepartmentQuery;
import org.lc.stk.web.dto.department.DepartmentResponse;
import org.lc.stk.web.dto.department.UpdateDepartmentRequest;
import org.lc.stk.web.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;

@RestController
@RequestMapping("/api/v1/departments")
@Tag(name = "部门管理", description = "部门的增删改查接口")
@Validated
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @PostMapping
    @Operation(summary = "创建部门")
    public ApiResponse<DepartmentResponse> create(@Valid @RequestBody CreateDepartmentRequest request) {
        Department department = departmentService.create(request);
        return ApiResponse.success(DepartmentResponse.fromEntity(department));
    }

    @PutMapping
    @Operation(summary = "更新部门")
    public ApiResponse<DepartmentResponse> update(@Valid @RequestBody UpdateDepartmentRequest request) {
        Department department = departmentService.update(request);
        return ApiResponse.success(DepartmentResponse.fromEntity(department));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除部门")
    public ApiResponse<Void> delete(
            @Parameter(description = "部门ID", required = true) 
            @PathVariable Integer id) {
        departmentService.delete(id);
        return ApiResponse.success();
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取部门详情")
    public ApiResponse<DepartmentResponse> getById(
            @Parameter(description = "部门ID", required = true) 
            @PathVariable Integer id) {
        Department department = departmentService.getById(id);
        return ApiResponse.success(DepartmentResponse.fromEntity(department));
    }

    @GetMapping
    @Operation(summary = "获取所有部门")
    public ApiResponse<List<DepartmentResponse>> getAll() {
        List<Department> departments = departmentService.getAll();
        List<DepartmentResponse> responseList = departments.stream()
                .map(DepartmentResponse::fromEntity)
                .collect(Collectors.toList());
        return ApiResponse.success(responseList);
    }

    @GetMapping("/tree")
    @Operation(summary = "获取部门树形结构")
    public ApiResponse<List<DepartmentResponse>> getTree() {
        List<Department> departments = departmentService.getTree();
        List<DepartmentResponse> responseList = departments.stream()
                .map(DepartmentResponse::fromEntity)
                .collect(Collectors.toList());
        return ApiResponse.success(responseList);
    }

    @GetMapping("/by-parent/{parentId}")
    @Operation(summary = "根据父部门ID获取子部门列表")
    public ApiResponse<List<DepartmentResponse>> getByParentId(
            @Parameter(description = "父部门ID") 
            @PathVariable(required = false) Integer parentId) {
        List<Department> departments = departmentService.getByParentId(parentId);
        List<DepartmentResponse> responseList = departments.stream()
                .map(DepartmentResponse::fromEntity)
                .collect(Collectors.toList());
        return ApiResponse.success(responseList);
    }

    @GetMapping("/query")
    @Operation(summary = "分页查询部门")
    public ApiResponse<List<DepartmentResponse>> query(
            @Parameter(description = "查询条件") 
            DepartmentQuery query,
            @Parameter(description = "页码(从0开始)", example = "0") 
            @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页大小", example = "10") 
            @RequestParam(defaultValue = "10") int size) {
        
        Sort sort = Sort.by(
            query.getSortDirection().equalsIgnoreCase("desc") ? 
            Sort.Direction.DESC : Sort.Direction.ASC, 
            query.getSortBy()
        );
        
        Page<Department> resultPage = departmentService.query(query, PageRequest.of(page, size, sort));
        
        List<DepartmentResponse> responseList = resultPage.getContent().stream()
                .map(DepartmentResponse::fromEntity)
                .collect(Collectors.toList());
        
        return ApiResponse.success(
            responseList,
            new ApiResponse.PageInfo(
                resultPage.getNumber(),
                resultPage.getSize(),
                resultPage.getTotalElements(),
                resultPage.getTotalPages()
            )
        );
    }

    @GetMapping("/exists/name/{name}")
    @Operation(summary = "检查部门名称是否存在")
    public ApiResponse<Boolean> checkNameExists(
            @Parameter(description = "部门名称", required = true) 
            @PathVariable String name,
            @Parameter(description = "排除的ID") 
            @RequestParam(required = false) Integer excludeId) {
        return ApiResponse.success(departmentService.isNameExists(name, excludeId));
    }

    @GetMapping("/exists/code/{code}")
    @Operation(summary = "检查部门编码是否存在")
    public ApiResponse<Boolean> checkCodeExists(
            @Parameter(description = "部门编码", required = true) 
            @PathVariable String code,
            @Parameter(description = "排除的ID") 
            @RequestParam(required = false) Integer excludeId) {
        return ApiResponse.success(departmentService.isCodeExists(code, excludeId));
    }
}